package com.baibei.ebec.follow.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.baibei.ebec.follow.adapter.LastOrdersAdapter;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.model.UserInfo;
import com.baibei.module.BasicFragment;
import com.baibei.sdk.BuildConfig;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by tang on 2018/8/13.
 */

public class LastOrdersFragment extends BasicFragment {
    @BindView(R2.id.rv)
    RecyclerView rv;
    Unbinder unbinder;

    private String followerId;
    private Activity activity;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_last_orders;
    }

    public static LastOrdersFragment newInstance(String followerId){
        Bundle args = new Bundle();
        args.putString("followerId",followerId);
        LastOrdersFragment fragment = new LastOrdersFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        followerId = arguments.getString("followerId");
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserInfo userInfo = SessionManager.getDefault().getUser();
                String userId = userInfo.getUserId()+"";
                String url = com.baibei.ebec.sdk.BuildConfig.API_BASE_URL+"ddq/api/v1/query/other/news/order_detail";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                map.put("userId",userId);
                map.put("followerId",followerId);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    final JSONObject jsonObject = new JSONObject(response.body().string());
                    if (!"SUCCESS".equals(jsonObject.optString("code"))){
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                            }
                        });
                        return;
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            setData(jsonObject.optJSONArray("data"));
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        ).start();
    }

    private void setData(JSONArray data) {
        if (rv == null) return;
        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        rv.setLayoutManager(llm);
        LastOrdersAdapter adapter = new LastOrdersAdapter(data);
        rv.setAdapter(adapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
